//
//  LoginMainViewController.m
//  SouthChina
//
//  Created by kc on 15/9/6.
//  Copyright (c) 2015年 科创. All rights reserved.
//  登陆主界面

#import "LoginMainViewController.h"
#import "AddressBookLeftViewController.h"
#import "TabbarViewController.h"

@interface LoginMainViewController ()<UITextFieldDelegate>
{
    UITextField *TXFieldNickName;//用户昵称
}
@end

@implementation LoginMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES];
    ////下面是移动校园门户登陆界面
    self.view.backgroundColor = [UIColor whiteColor];
    [self addTitleBarWithBackBtn:@"移动校园门户" needReturn:NO];
    //昵称输入框
    TXFieldNickName = [[UITextField alloc]initWithFrame:CGRectMake(20, TITLE_BAR_HEGIHT+YNEW+25, SCREEN_WIDTH-20,30)];
    TXFieldNickName.placeholder = @"请输入您的昵称";
    TXFieldNickName.delegate = self;
    [TXFieldNickName becomeFirstResponder];
    [self.view addSubview:TXFieldNickName];
    
    //背景
    UILabel *lbBack = [[UILabel alloc]initWithFrame:CGRectMake(10,TXFieldNickName.frame.origin.y+TXFieldNickName.frame.size.height+10, SCREEN_WIDTH-20, 2)];
    lbBack.backgroundColor = [UIColor colorWithRed:25.0f/255.0f green:25.0f/255.0f blue:112.0f/255.0f alpha:1.0f]
    ;
    [self.view addSubview:lbBack];
    
    //按钮
    UIButton *btLoginEX = [[UIButton alloc]initWithFrame:CGRectMake(10, lbBack.frame.origin.y+lbBack.frame.size.height+20, SCREEN_WIDTH-20, 50)];
    btLoginEX.backgroundColor = BASIC_BLUE_COLOR;
    [btLoginEX addTarget:self action:@selector(btClickedLoginEX:) forControlEvents:UIControlEventTouchUpInside];
    [btLoginEX setTitle:@"开始试用" forState:UIControlStateNormal];
    btLoginEX.layer.masksToBounds = YES;
    btLoginEX.layer.cornerRadius = 10;
    [self.view addSubview:btLoginEX];
}

//开始试用
-(void)btClickedLoginEX:(id)sender
{
    [TXFieldNickName resignFirstResponder];
    BOOL bFirst = NO;
    
    //登陆时判断是否首次安装这个应用，如果是，不用更新数据库
    if ([DE getGlobalVar:LOGIN_USER_REALID]==nil) {
        bFirst = YES;
    }
    else
    {
        if(![[DE getGlobalVar:LOGIN_USER_REALID] isEqualToString:_LoginId.text]) //不是上次用户
        {
            NSString *sversion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", _LoginId.text,[DE getGlobalVar:CONTACT_VERSION]]];
            if(sversion == nil)
                bFirst = YES;
        }
    }
    
    NSString *mobile = TXFieldNickName.text;
    if (mobile.length==0) {
        [self showAlerHUD:@"请输入用户昵称！"];
        return;
    }
    
    //NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", mobile,[DE getGlobalVar:CONTACT_VERSION]]];
    //NSDictionary *userInfo = @{@"nickName":mobile,@"AddressBookVersion":addVersion==nil?@"0":addVersion};
    NSDictionary *userInfo = @{@"nickName":mobile,@"AddressBookVersion":@"0"};
    
    
    [DE serverCall:@"loginCheckForDemo" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if (success) {
                if (data) {
                    NSDictionary* userinfo = [data objectForKey:@"userinfo"];
                    
                    [DE setGlobalVar:LOGIN_USER_ORGID value:[userinfo objectForKey:@"refId"]];
                    [DE setGlobalVar:LOGIN_USER_ID value:[userinfo objectForKey:@"userId"]]; //学工号
                    [DE setGlobalVar:LOGIN_USER_PASSWORD value:[userinfo objectForKey:@"pwd"]];
                    [DE setGlobalVar:LOGIN_USER_REALID value:mobile];
                    
                    [DE setGlobalVar:LOGIN_USER_NAME value:object2Str([userinfo objectForKey:@"userName"])];
                    [DE setGlobalVar:LOGIN_USER_TYPE value:object2Str([userinfo objectForKey:@"type"])];
                    [DE setGlobalVar:LOGIN_USER_SEX value:object2Str([userinfo objectForKey:@"sex"])];
                    [DE setGlobalVar:LOGIN_USER_DEPT value:object2Str([userinfo objectForKey:@"dept"])];
                    [DE setGlobalVar:LOGIN_USER_PROFNAME value:object2Str([userinfo objectForKey:@"profName"])];
                    [DE setGlobalVar:LOGIN_USER_CLASS value:object2Str([userinfo objectForKey:@"className"])];
                    [DE setGlobalVar:LOGIN_USER_HEADIMG value:object2Str([userinfo objectForKey:@"headImg"])];
                    [DE setGlobalVar:LOGIN_USER_FRIEDNRANG value:object2Str([userinfo objectForKey:@"friendRange"])];
                    [DE setGlobalVar:LOGIN_USER_HOMETEL value:object2Str([userinfo objectForKey:@"fixedTel"])];
                    [DE setGlobalVar:LOGIN_USER_MOBILE value:object2Str([userinfo objectForKey:@"phone"])];
                    [DE setGlobalVar:LOGIN_USER_EMAIL value:object2Str([userinfo objectForKey:@"email"])];
                    [DE setGlobalVar:LOGIN_USER_ADDRESS value:object2Str([userinfo objectForKey:@"address"])];
                    [DE setGlobalVar:LOGIN_USER_NICKNAME value:object2Str([userinfo objectForKey:@"nickName"])];
                    [DE setGlobalVar:LOGIN_USER_QQ value:object2Str([userinfo objectForKey:@"qq"])];
                    [DE setGlobalVar:LOGIN_USER_PROV value:object2Str([userinfo objectForKey:@"prov"])];
                    [DE setGlobalVar:LOGIN_USER_CITY value:object2Str([userinfo objectForKey:@"city"])];
                    //20150708增加个人标签
                    [DE setGlobalVar:LOGIN_USER_TAGS value:object2Str([userinfo objectForKey:@"userTags"])];
                    //20150709增加工作状态
                    [DE setGlobalVar:LOGIN_USER_WORKSTATUS value:object2Str([userinfo objectForKey:@"workStatus"])];
                    //20150713增加学工号,调用接口发现好像不正确了
                    [DE setGlobalVar:LOGIN_USER_REALUSERID value:object2Str([userinfo objectForKey:@"realUserId"])];
                    //  [DE setGlobalVar:LOGIN_USER_REALUSERID value:object2Str([userinfo objectForKey:@"userId"])];
                    //20150813用户linkInfoState LOGIN_USER_LINKINFOSTATE
                    [DE setGlobalVar:LOGIN_USER_LINKINFOSTATE value:object2Str([userinfo objectForKey:@"linkInfoState"])];
                    NSLog(@"check in linkInfoState：%@",object2Str([userinfo objectForKey:@"linkInfoState"]));
                }
                
                //检查数据库是否需要重建
                if (bFirst) {
                    NSLog(@"第一次安装");
                    [DE setGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],DATABASEVERSION] value:CURDATABASEVERSION];
                }
                else
                {
                    if ([self CheckUpdateBase]) {
                        return ;
                    }
                }
                
                //上传deviceToken到服务器
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSString *deviceToken = [defaults objectForKey:@"deviceToken"];
                
                if (deviceToken && [deviceToken length] > 0) {
                    NSDictionary *para = [NSDictionary dictionaryWithObject:deviceToken forKey:@"deviceToken"];
                    [DE serverCall:@"confirmMsg" params:para callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param){
                        if (success) {
                            NSLog(@"send deviceToken to server success! ");
                        }else{
                            NSLog(@"send deviceToken to server failed!");
                        }
                    }];
                }
                
                AddressBookLeftViewController *colorsVC = [[AddressBookLeftViewController alloc] init];
                colorsVC.isCreatGroup = NO;
                TabbarViewController *tabView = [[TabbarViewController alloc] init];
                ICSDrawerController *mainDrawer = [[ICSDrawerController alloc] initWithLeftViewController:colorsVC
                                                                                     centerViewController:tabView];
                kAppDelegate.iCSDrawerController = mainDrawer;
                [self.navigationController setViewControllers:@[mainDrawer] animated:YES];
                
                
                
            }else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:desc delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alert.tag = 101;
                [alert show];
                
            }
        });
        
    }];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//回退
-(void)btnBack{
    [self.navigationController popViewControllerAnimated:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [TXFieldNickName resignFirstResponder];
    return YES;
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (IBAction)btClickedLogin:(id)sender {
    [_LoginId resignFirstResponder];
    [_LoginPassword resignFirstResponder];
    
    BOOL bFirst = NO;
    
    //20151013 _LoginId.text即为 LOGIN_USER_REALID
    //登陆时判断是否首次安装这个应用，如果是，不用更新数据库
    if ([DE getGlobalVar:LOGIN_USER_REALID]==nil) {
        bFirst = YES;
    }
    else
    {
        if(![[DE getGlobalVar:LOGIN_USER_REALID] isEqualToString:_LoginId.text]) //不是上次用户
        {
            NSString *sversion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", _LoginId.text,[DE getGlobalVar:CONTACT_VERSION]]];
            if(sversion == nil)
                bFirst = YES;
        }
    }
    
    
    NSString *mobile = _LoginId.text;
    NSString *pwd = _LoginPassword.text;
    
    if (mobile.length==0 || pwd.length==0) {
        [self showAlerHUD:@"请输入用户名和密码！"];
        return;
    }
    
    NSLog(@"buttonActionLogin == %@",DE.deviceToken);
    
    
    NSString* device_token = [NSString stringWithFormat:@"%@",DE.deviceToken];
    
    NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", mobile,[DE getGlobalVar:CONTACT_VERSION]]];
    NSDictionary *userInfo = @{@"USER_NAME":mobile,@"USER_PASSWORD":pwd,@"AddressBookVersion":addVersion==nil?@"0":addVersion,@"device_token":device_token};
    //[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [DE serverCall:@"loginCheck" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if (success) {
                if (data) {
                    NSDictionary* userinfo = [data objectForKey:@"userinfo"];
                    
                    [DE setGlobalVar:LOGIN_USER_ORGID value:[userinfo objectForKey:@"refId"]];
                    [DE setGlobalVar:LOGIN_USER_ID value:[userinfo objectForKey:@"userId"]]; //学工号
                    [DE setGlobalVar:LOGIN_USER_PASSWORD value:[userinfo objectForKey:@"pwd"]];
                    [DE setGlobalVar:LOGIN_USER_REALID value:mobile];
                    
                    [DE setGlobalVar:LOGIN_USER_NAME value:object2Str([userinfo objectForKey:@"userName"])];
                    [DE setGlobalVar:LOGIN_USER_TYPE value:object2Str([userinfo objectForKey:@"type"])];
                    [DE setGlobalVar:LOGIN_USER_SEX value:object2Str([userinfo objectForKey:@"sex"])];
                    [DE setGlobalVar:LOGIN_USER_DEPT value:object2Str([userinfo objectForKey:@"dept"])];
                    [DE setGlobalVar:LOGIN_USER_PROFNAME value:object2Str([userinfo objectForKey:@"profName"])];
                    [DE setGlobalVar:LOGIN_USER_CLASS value:object2Str([userinfo objectForKey:@"className"])];
                    [DE setGlobalVar:LOGIN_USER_HEADIMG value:object2Str([userinfo objectForKey:@"headImg"])];
                    [DE setGlobalVar:LOGIN_USER_FRIEDNRANG value:object2Str([userinfo objectForKey:@"friendRange"])];
                    [DE setGlobalVar:LOGIN_USER_HOMETEL value:object2Str([userinfo objectForKey:@"fixedTel"])];
                    [DE setGlobalVar:LOGIN_USER_MOBILE value:object2Str([userinfo objectForKey:@"phone"])];
                    [DE setGlobalVar:LOGIN_USER_EMAIL value:object2Str([userinfo objectForKey:@"email"])];
                    [DE setGlobalVar:LOGIN_USER_ADDRESS value:object2Str([userinfo objectForKey:@"address"])];
                    [DE setGlobalVar:LOGIN_USER_NICKNAME value:object2Str([userinfo objectForKey:@"nickName"])];
                    [DE setGlobalVar:LOGIN_USER_QQ value:object2Str([userinfo objectForKey:@"qq"])];
                    [DE setGlobalVar:LOGIN_USER_PROV value:object2Str([userinfo objectForKey:@"prov"])];
                    [DE setGlobalVar:LOGIN_USER_CITY value:object2Str([userinfo objectForKey:@"city"])];
                    //20150708增加个人标签
                    [DE setGlobalVar:LOGIN_USER_TAGS value:object2Str([userinfo objectForKey:@"userTags"])];
                    //20150709增加工作状态
                    [DE setGlobalVar:LOGIN_USER_WORKSTATUS value:object2Str([userinfo objectForKey:@"workStatus"])];
                    //20150713增加学工号,调用接口发现好像不正确了
                    [DE setGlobalVar:LOGIN_USER_REALUSERID value:object2Str([userinfo objectForKey:@"realUserId"])];
                    //  [DE setGlobalVar:LOGIN_USER_REALUSERID value:object2Str([userinfo objectForKey:@"userId"])];
                    //20150813用户linkInfoState LOGIN_USER_LINKINFOSTATE
                    [DE setGlobalVar:LOGIN_USER_LINKINFOSTATE value:object2Str([userinfo objectForKey:@"linkInfoState"])];
                    NSLog(@"check in linkInfoState：%@",object2Str([userinfo objectForKey:@"linkInfoState"]));
                }
                //检查数据库是否需要重建
                if (bFirst) {
                    NSLog(@"第一次安装");
                    [DE setGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],DATABASEVERSION] value:CURDATABASEVERSION];
                }
                else
                {
                    if ([self CheckUpdateBase]) {
                        return ;
                    }
                }
                
                //上传deviceToken到服务器
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSString *deviceToken = [defaults objectForKey:@"deviceToken"];
                
                if (deviceToken && [deviceToken length] > 0) {
                    NSDictionary *para = [NSDictionary dictionaryWithObject:deviceToken forKey:@"deviceToken"];
                    [DE serverCall:@"confirmMsg" params:para callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param){
                        if (success) {
                            NSLog(@"send deviceToken to server success! ");
                        }else{
                            NSLog(@"send deviceToken to server failed!");
                        }
                    }];
                }
                
                AddressBookLeftViewController *colorsVC = [[AddressBookLeftViewController alloc] init];
                colorsVC.isCreatGroup = NO;
                TabbarViewController *tabView = [[TabbarViewController alloc] init];
                ICSDrawerController *mainDrawer = [[ICSDrawerController alloc] initWithLeftViewController:colorsVC
                                                                                     centerViewController:tabView];
                kAppDelegate.iCSDrawerController = mainDrawer;
                [self.navigationController setViewControllers:@[mainDrawer] animated:YES];
                
                
                
            }else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:desc delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alert.tag = 101;
                [alert show];
                
            }
        });
        
    }];
    
}

-(BOOL) CheckUpdateBase{
    
    NSString *dataVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],DATABASEVERSION]];
    NSLog(@"databasevision.......%@",dataVersion);
    //是否为当前版本号，不是的话，需要更新数据库
    if (![dataVersion isEqualToString:CURDATABASEVERSION]) {
        //更新数据库版本号
        [DE setGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],DATABASEVERSION] value:CURDATABASEVERSION];
        NSLog(@"需要更新数据库");
        [self UpdateDataBase];
        return TRUE;
    }
    return FALSE;
}

-(void)UpdateDataBase{
    //先删除所有表，再重建所有表，清空用户名和密码，强制用户重新登录，最后设置版本号为当前版本号
    FMDatabase *_dataBase = [DateBaseHelper openDateBase];
    NSLog(@"创建表的位置：%@",DE.dataPath);
    //contacts
    NSString *sdelsql = @"DROP  TABLE IF EXISTS 'contacts'";
    NSString *createStr=@"CREATE  TABLE  IF NOT EXISTS 'contacts' ('PK_ID' text PRIMARY KEY  NOT NULL  UNIQUE ,'ID' text,'NAME' text, 'PROF_NAME' text,'CLASS_NAME' text,'NJ' text,'HEAD_IMG' text,'SEX' text,'QP' text,'REF_ID' text,'TYPE' text,'DEPT' text,'OPERATE' text,'IS_ACTIVATED' text,'CREATE_USER' text ,'ORG_TYPE' text,'HAS_CHILD' text,'OTHER_INFO' text,'UPDATE_TIME' date)";
    [_dataBase executeUpdate:sdelsql];
    BOOL worked = [_dataBase executeUpdate:createStr];
    FMDBQuickCheck(worked);
    
    //datadict
    sdelsql = @"DROP  TABLE  IF EXISTS 'datadict'";
    createStr=@"CREATE  TABLE  IF NOT EXISTS 'datadict' ('dictdataId' text PRIMARY KEY  NOT NULL  UNIQUE ,'dictdataName' text,'dictdataOrder' text, 'dictdataValue' text,'dicttypeId' text,'dictdataDesc' text,'OTHER_INFO' text,'UPDATE_TIME' date)";
    [_dataBase executeUpdate:sdelsql];
    worked = [_dataBase executeUpdate:createStr];
    FMDBQuickCheck(worked);
    
    //keybooks
    sdelsql = @"DROP  TABLE IF EXISTS 'keybooks'";
    createStr=@"CREATE  TABLE  IF NOT EXISTS 'keybooks' ('kid' text PRIMARY KEY  NOT NULL  UNIQUE ,'words'  text,'OTHER_INFO' text,'UPDATE_TIME' date)";
    [_dataBase executeUpdate:sdelsql];
    worked = [_dataBase executeUpdate:createStr];
    FMDBQuickCheck(worked);
    
    //message
    sdelsql = @"DROP  TABLE IF EXISTS 'message'";
    createStr=@"CREATE  TABLE  IF NOT EXISTS 'message' ('id' text PRIMARY KEY  NOT NULL  UNIQUE ,'receiverId' text,'sequences' text, 'user_id' text,'senderId' text,'messageType' text,'mediaType' text,'state' text,'length' text,'mesSesion_sess_id' text ,'ut_id' text,'text' text,'OTHER_INFO' text,'UPDATE_TIME' date)";
    [_dataBase executeUpdate:sdelsql];
    worked = [_dataBase executeUpdate:createStr];
    FMDBQuickCheck(worked);
    
    //messagesession
    sdelsql = @"DROP  TABLE  IF EXISTS  'messagesession'";
    createStr=@"CREATE  TABLE  IF NOT EXISTS 'messagesession' ('sess_id' text PRIMARY KEY  NOT NULL  UNIQUE ,'sessionPic' text,'text' text, 'title' text,'badgeNumber' int,'sessionType' text,'oppositeId' text,'isremind' text,'OTHER_INFO' text,'UPDATE_TIME' date)";
    [_dataBase executeUpdate:sdelsql];
    worked = [_dataBase executeUpdate:createStr];
    FMDBQuickCheck(worked);
    
    //publicaccount
    sdelsql = @"DROP  TABLE  IF EXISTS 'publicaccount'";
    createStr=@"CREATE  TABLE  IF NOT EXISTS 'publicaccount' ('appId' text PRIMARY KEY  NOT NULL  UNIQUE ,'appName' text,'type' text, 'sort' text,'qp' text,'initialWord' text,'funcDesc' text,'headImg' text,'subscribeStatus' text,'isRecommend' text,'isReceive' text,'disableChat' text,'OTHER_INFO' text,'UPDATE_TIME' date,'isBasic' text,'isBanner' text,'appType' text,'isHome' text,'userSort' text)";
    [_dataBase executeUpdate:sdelsql];
    worked = [_dataBase executeUpdate:createStr];
    FMDBQuickCheck(worked);
    
    //TODO 当前用户通讯录版本号设置为空，公众号版本号设置为空，关键字版本号设置为空
    //最后 才把userid设置为空  //[DE setUserId:@""];
    //清空用户通讯录版本号
    [DE setGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]] value:@""];
    
    NSString *sversion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
    
    NSLog(@"GENGXINHOU %@",sversion);
    //清空关键字版本号：
    [DE setGlobalVar:[NSString stringWithFormat:@"%@_%@",DE.userId,@"keyBookVersion"] value:@""];
    //清空用户ID
    [DE setUserId:@""];
    
    //提示有数据库版本更新20151015
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"因客户端升级，数据需要做同步更新，需要您再次登录，由此带来的不便，敬请谅解！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    alert.tag = 102;
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag==102 && buttonIndex==0)
    {
        LoginMainViewController *lgoin = [[LoginMainViewController alloc] init];
        lgoin.TypeLoginMain = @"1";
        [self.navigationController setViewControllers:@[lgoin]];
    }
}

@end
